import { getDicts } from '@/api/index.js';
import download from '@/utils/dowload';

import { $dayjs } from '@/main.js'; // ES 2015
var mixins = {
	created() {},
	mounted() {},
	data() {
		return {};
	},
	methods: {
		_set(row, key, value) {
			this.$set(row, key, value);
		},
		_formatTime(time, reg) {
			switch (reg) {
				case 0:
					reg = 'YYYY-MM-DD';
					break;
				case 1:
					reg = 'YYYY-MM-DD HH:mm:ss';
					break;
			}
			let pass = dayjs(time).isValid();
			if (!pass) return time;

			return dayjs(time).format(reg);
		},
		_getDicts(data) {
			if (!data) Promise.resolve([]);
			return new Promise((resolve, reject) => {
				getDicts(data)
					.then(response => {
						resolve(response.data ?? []);
					})
					.catch(() => {
						resolve([]);
					});
			});
		},

		_valid(form, event = 'validate') {
			return new Promise(resolve => {
				form[event]()
					.then(res => {
						resolve(true);
					})
					.catch(err => {
						resolve(err);
					});
			});
		},
		_validate() {
			return new Promise(async resolve => {
				let result = true;
				let error = [];
				let refs = Object.values(this.$refs);
				for (let index = 0; index < refs?.length; index++) {
					const ref = refs[index];
					if (
						Object.prototype.toString.call(ref) == '[object Array]'
					) {
						for (let i = 0; i < ref.length; i++) {
							const element = ref[i];
							if (element?._validate) {
								let rc = await element?._validate?.();
								let pass = true;
								if (Array.isArray(rc)) {
									pass = false;
									error.push(...rc);
								}
								result = result && pass;
							}
							if (element?.$options.name === 'uniForms') {
								let rf = await this._valid(ref);
								let pass = true;
								if (Array.isArray(rf)) {
									pass = false;
									error.push(...rf);
								}
								result = result && pass;
							}
						}
					} else {
						if (ref?._validate) {
							let rc = await ref?._validate?.();

							let pass = true;
							if (Array.isArray(rc)) {
								pass = false;
								error.push(...rc);
							}
							result = result && pass;
						}
						if (ref?.$options.name === 'uniForms') {
							let rf = await this._valid(ref);
							let pass = true;
							if (Array.isArray(rf)) {
								pass = false;
								error.push(...rf);
							}
							result = result && pass;
						}
					}
				}

				resolve(result ? result : error);
			});
		},
		_clearValidate() {
			let refs = Object.values(this.$refs);
			for (let index = 0; index < refs?.length; index++) {
				const ref = refs[index];
				if (Object.prototype.toString.call(ref) == '[object Array]') {
					for (let i = 0; i < ref.length; i++) {
						const element = ref[i];
						if (element?._clearValidate) {
							element?._clearValidate?.();
						}
						if (element?.clearValidate) {
							element.clearValidate?.();
						}
					}
				} else {
					if (ref?._clearValidate) {
						ref?._clearValidate?.();
					}
					if (ref?.clearValidate) {
						ref.clearValidate?.();
					}
				}
			}
		},
		// 下载
		_download(url, id, name) {
			download({
				url: `${url}/${id}`,
				method: 'get',
			}).then(res => {
				wx.getFileSystemManager().saveFile({
					tempFilePath: res,
					success: function (res) {
						var filePath = res.savedFilePath;
						uni.showModal({
							title: '提示',
							content: '文件已保存：' + name ? name : filePath,
							cancelText: '关闭',
							confirmText: '打开文件',
							success: res2 => {
								if (res2.confirm) {
									uni.openDocument({
										filePath: filePath,
										showMenu: true,
									});
								}
							},
						});
					},
				});
			});
		},
		_dataload() {
			this.$nextTick(() => {
				this.dataload?.();
				let refs = Object.values(this.$refs);
				for (let index = 0; index < refs?.length; index++) {
					const ref = refs[index];
					if (
						Object.prototype.toString.call(ref) == '[object Array]'
					) {
						for (let i = 0; i < ref.length; i++) {
							const element = ref[i];
							element?._dataload?.();
							// if (element?.dataload) {
							// 	element?.dataload?.();
							// }
						}
					} else {
						ref?._dataload?.();
						// if (ref?.dataload) {
						// 	ref?.dataload?.();
						// }
					}
				}
			});
		},
		// 判空
		isNoEmpty(value) {
			if (value === null || value === undefined || value === '') {
				return '--';
			} else {
				return value;
			}
		},
		_resetFields(config = []) {
			let configs = config;
			if (Object.prototype.toString.call(config) === '[object Object]') {
				configs = [config];
			}
			for (let index = 0; index < configs.length; index++) {
				let child = configs[index];
				const form = this.$refs[child.ref ?? 'form'];
				if (!form) continue;
				Object.keys(form.formRules).map(item => {
					this.$set(child.data, item, undefined);
				});
			}
		},

		async _scrollToError() {
			let node = await this._getErrorNode();
			if (this.notEmpty(node)) {
				return node;
			}
			let refs = Object.values(this.$refs);
			scroll: for (let index = 0; index < refs?.length; index++) {
				const ref = refs[index];
				if (Object.prototype.toString.call(ref) == '[object Array]') {
					for (let i = 0; i < ref.length; i++) {
						const element = ref[i];
						if (element?._scrollToError) {
							let node = await element?._scrollToError?.();
							if (node) {
								return node;
							}
						}
						if (element?.$options?.name == 'uniForms') {
							for (
								let c = 0;
								c < element?.$children.length;
								c++
							) {
								const child = element?.$children[c];
								let node = await child?._scrollToError?.();
								if (node) {
									return node;
								}
							}
						}
					}
				} else {
					if (ref?._scrollToError) {
						let node = await ref?._scrollToError?.();
						if (node) {
							return node;
						}
					}
					if (ref?.$options?.name == 'uniForms') {
						for (let c = 0; c < ref?.$children.length; c++) {
							const child = ref?.$children[c];
							let node = await child?._scrollToError?.();
							if (node) {
								return node;
							}
						}
					}
				}
			}
		},
		_getErrorNode() {
			return new Promise(resolve => {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query
						.select('.uni-forms-item__error.msg--active')
						.boundingClientRect(data => {
							resolve(data);
						})
						.exec();
				}, 0);
			});
		},
	},
	computed: {},
	filters: {
		_setEmpty(row) {
			if (row === undefined || row === null || row === '') {
				return '-';
			} else {
				return row;
			}
		},
		_getChain(row, prop) {
			if (
				Object.prototype.toString.call(prop) !== '[object String]' &&
				Object.prototype.toString.call(prop) !== '[object Array]'
			) {
				return '--';
			}
			let data = [];
			if (typeof prop === 'string') {
				data = prop.split('.');
			}
			let result = data.reduce(function (prev, next) {
				return prev?.[next];
			}, row);
			return result ?? '--';
		},
		_getIDCard(data) {
			let res = '--';
			res =
				data?.replace(/^(.{6})(?:\w+)(.{4})$/, '$1********$2') ?? '--';

			return res;
		},
		_translateDict(value, dictList) {
			if (!dictList) return value;
			let dict = dictList.find(
				item => (item.value ?? item.dictValue) === value,
			);
			if (dict) return dict.label ?? dict.dictLabel;
			return '-';
		},
	},
};

export default mixins;
